package me.zhengjie.common.utils

import me.zhengjie.common.exception.BadRequestException
import org.hibernate.exception.ConstraintViolationException
import java.io.PrintWriter
import java.io.StringWriter


/**
 * 异常工具 2019-01-06
 * @author Kuki Wu
 */
object ThrowableUtil {
    /**
     * 获取堆栈信息
     */
    @JvmStatic
    fun getStackTrace(throwable: Throwable): String {
        val sw = StringWriter()
        PrintWriter(sw).use { pw ->
            throwable.printStackTrace(pw)
            return sw.toString()
        }
    }

    @JvmStatic
    fun throwForeignKeyException(e: Throwable, msg: String?) {
        var t = e.cause
        while (t != null && t !is ConstraintViolationException) {
            t = t.cause
        }
        if (t != null) {
            throw BadRequestException(msg)
        }
        assert(false)
        throw BadRequestException("删除失败：" + msg)
    }
}